/**
 * @作者 伟子涵
 * @微信公号 搬砖暗夜码农
 * @开源项目 $ https://gitee.com/zhouwei5208888
 * @我的博客 $ http://itzhouwei.com
 * @创建时间 2023/12/18  14:47
 */
package com.itzhouwei.commerce.thread.core.demo8;

/**
 * @description: 有字符111111...，222222...，请使用多线程编程实现输出121212121212... java
 * @author：zw，微信：yingshengzw
 * @date: 2023/12/18  14:47 
 * @Copyright： 公众号：搬砖暗夜码农 | 博客：https://itzhouwei.com - 沉淀、分享、成长，让自己和他人都能有所收获！
 */
public class PrintNumbers02 {

    private final Object monitor = new Object();
    private volatile boolean printOne = true;

    class PrintOne implements Runnable {
        public void run() {
            for (int i = 0; i < 10; i++) {
                synchronized (monitor) {
                    while (!printOne) {
                        try {
                            monitor.wait();
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                        }
                    }
                    System.out.print(1);
                    printOne = false;
                    monitor.notifyAll();
                }
            }
        }
    }

    class PrintTwo implements Runnable {
        public void run() {
            for (int i = 0; i < 10; i++) {
                synchronized (monitor) {
                    while (printOne) {
                        try {
                            monitor.wait();
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                        }
                    }
                    System.out.print(2);
                    printOne = true;
                    monitor.notifyAll();
                }
            }
        }
    }

    public void startPrinting() {
        new Thread(new PrintOne()).start();
        new Thread(new PrintTwo()).start();
    }

}
